<template>
	<cu-page-base :nav-bar-options="navBarOptions" @clickNavBarLeft="goBack">
		<view class="cu-w-100 cu-p-20">
			<view
				class="cu-w-100 cu-p-20 cu-bg-main cu-border-r-20 cu-shadow cu-d-flex cu-flex-column cu-j-sb cu-a-center">
				<view class="cu-w-100">
					<audio class="cu-w-100" style="text-align: left" :src="recordStore.compoundList[idx].url"
						:name="recordStore.compoundList[idx]._id" author="暂无" :action="audioAction" controls></audio>
				</view>
				<view class="cu-w-100 cu-py-10">
					<u-button @click="downLoad(recordStore.compoundList[idx].url)" text="下载音频" shape="circle"
						color="linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))"></u-button>
				</view>
				<view class="cu-w-100 cu-py-10">
					<u-button @click="copyBtn(recordStore.compoundList[idx].text)" text="复制文案" shape="circle"
						color="linear-gradient(to right, rgb(220, 194, 11), rgb(4, 151, 99))"></u-button>
				</view>
				<!-- <view class="cu-w-100 cu-py-10">
					<u-button
						@click="downLoadLrc(recordStore.compoundList[idx]._id,recordStore.compoundList[idx].subtitles)"
						text="下载Lrc字幕" shape="circle"
						color="linear-gradient(to right, rgb(4, 151, 99), rgb(255, 170, 127))"></u-button>
				</view> -->
				<view class="cu-w-100 cu-py-10">
					<u-button
						@click="downLoadSrt(recordStore.compoundList[idx]._id,recordStore.compoundList[idx].subtitles)"
						text="下载Srt字幕" shape="circle"
						color="linear-gradient(to right, rgb(255, 170, 127), rgb(85, 170, 255))"></u-button>
				</view>
				<view class="cu-w-100 cu-py-10 cu-d-flex cu-flex-column cu-j-sb cu-a-stretch">
					<view class="cu-text-danger">备注：</view>
					<view class="cu-text-danger"><text class="cu-px-20"></text>配音文件仅保留3天，请尽快下载保存</view>
					<view class="cu-text-danger"><text class="cu-px-20"></text>音频文件，请通过浏览器访问下载地址，进行下载</view>
				</view>
			</view>
			<view class="progress-container" v-if="isShowProgress">
				<view class="progress-box">
					<view class="text">{{tips}}</view>
					<progress :percent="progress" show-info stroke-width="3" />
				</view>
			</view>
		</view>
	</cu-page-base>

</template>

<script>
	const {
		getRealTextByText,
		getAudioTextLrcMap,
		getAudioTextSrtMap
	} = require("@/pages/voice/utils/voice/index")

	import {
		mapState
	} from 'vuex';
	import commMiXin from '@/common/mixin/common-mixin.js';
	export default {
		mixins: [commMiXin],
		computed: {
			...mapState({
				recordStore: state => state.recordStore,
			})
		},
		data() {
			return {
				navBarOptions: {
					title: "详情",
					leftText: "返回",
					leftIcon: "back",
				},
				idx: 0,
				audioAction: {
					method: 'pause'
				},
				isShowProgress: false,
				progress: 0,
				tips: "文件下载中，请稍后......"
			};
		},
		onLoad(e) {
			const {
				idx
			} = e
			if (idx !== undefined) {
				this.idx = idx
			}
		},
		methods: {
			copyBtn(data) {
				data = getRealTextByText(data);
				uni.setClipboardData({
					data: data,
					success: function() {
						uni.showToast({
							icon: 'success',
							title: "已复制文案",
							duration: 1500
						})
					},
					fail: function(err) {}
				});
			},
			downLoad(url) {
				uni.setClipboardData({
					data: url,
					success: function() {
						uni.showToast({
							icon: 'success',
							title: "已复制下载地址",
							duration: 1500
						})
					},
					fail: function(err) {}
				});
			},
			goBack(data) {
				this.gotoPage(1, 'navigateBack');
			},
			downloadFile(url) {
				if (url === undefined) {
					uni.showToast({
						icon: 'error',
						title: '下载失败',
						duration: 1500
					})
					return
				}
				this.tips = "文件下载中，请稍后......"
				const fileSystemManager = uni.getFileSystemManager();
				const downloadTask = uni.downloadFile({
					url: url,
					success: res => {
						let that = this;
						if (res.statusCode === 200) {
							this.tips = "正在保存，请稍后......"
							fileSystemManager.saveFile({
								tempFilePath: res.tempFilePath,
								success: function(resp) {
									console.log(resp)
									fileSystemManager.copyFile({
										srcPath: resp.savedFilePath,
										destPath: `${uni.env.USER_DATA_PATH}/test.mp3`,
										success(res) {
											that.isShowProgress = false;
											console.log(res);


											uni.showModal({
												title: '提示',
												content: '文件已保存：' +
													`${uni.env.USER_DATA_PATH}/test.mp3`,
												cancelText: '我知道了',
												confirmText: '打开文件',
												success: function(res1) {
													if (res1.confirm) {
														uni.openDocument({
															filePath: `${uni.env.USER_DATA_PATH}/test.mp3`,
															success: (
																sus
															) => {
																console
																	.log(
																		"文件打开成功"
																	)
															}
														})
													}
												},
												fail: () => {
													uni.showToast({
														icon: 'error',
														title: '保存失败',
														duration: 1500
													})
												},
												complete: () => {
													uni.setClipboardData({
														data: `${uni.env.USER_DATA_PATH}/test.mp3`,
														success: function() {
															uni.showToast({
																icon: 'success',
																title: "已复制保存文件路径",
																duration: 1500
															})
														},
														fail: function(
															err) {}
													});
												}
											});
										},
										fail(res) {
											console.error(res)
										}
									})

								},
								fail: function(resp) {
									uni.showToast({
										icon: 'error',
										title: '保存失败',
										duration: 1500
									})
								},
								complete: function() {
									that.isShowProgress = false;
								}
							})


						}

					},
					fail: () => {
						uni.showToast({
							icon: 'error',
							title: '下载失败',
							duration: 1500
						})
					}
				})

				downloadTask.onProgressUpdate((res) => {
					if (res.progress > 0) {
						this.isShowProgress = true;
					}
					this.progress = res.progress;
					// console.log('下载进度：' + res.progress);
					// console.log('已下载长度：' + res.totalBytesWritten);
					// console.log('文件总长度：' + res.totalBytesExpectedToWrite);
				})
			},
			downLoadLrc(id, subtitles) {
				if (subtitles == null || subtitles.length <= 0) {
					uni.showToast({
						icon: 'error',
						title: '内容不存在',
						duration: 1500
					})
				} else {
					const outPutMap = getAudioTextLrcMap(subtitles)
					if (outPutMap && outPutMap.length > 0) {
						let outPutStr = "";
						for (let item of outPutMap) {
							outPutStr = outPutStr + item.time + " " + item.text + "\r\n";
						}
						// 输出数据校验
						if (outPutStr === "") {
							uni.showToast({
								icon: 'error',
								title: '输出内容为空',
								duration: 1500
							})
							return
						}
						// console.log(outPutStr)
						this.writeFile("str" + id + ".lrc", outPutStr)
					} else {
						uni.showToast({
							icon: 'error',
							title: '数据转换失败',
							duration: 1500
						})
					}
				}
			},
			downLoadSrt(id, subtitles) {
				if (subtitles == null || subtitles.length <= 0) {
					uni.showToast({
						icon: 'error',
						title: '内容不存在',
						duration: 1500
					})
				} else {
					const outPutMap = getAudioTextSrtMap(subtitles)
					if (outPutMap && outPutMap.length > 0) {
						let outPutStr = "";
						let count = 1;
						for (let item of outPutMap) {
							if (count === 1) {
								outPutStr = outPutStr + count;
							} else {
								outPutStr = outPutStr + "\r\n" + count;
							}
							outPutStr = outPutStr + "\r\n" + item.starttime + " --> " + item.endtime + "\r\n" + item.text +
								"\r\n";
							count++;
						}
						// 输出数据校验
						if (outPutStr === "") {
							uni.showToast({
								icon: 'error',
								title: '输出内容为空',
								duration: 1500
							})
							return
						}
						// console.log(outPutStr)
						this.writeFile("str" + id + ".srt", outPutStr)
					} else {
						uni.showToast({
							icon: 'error',
							title: '数据转换失败',
							duration: 1500
						})
					}

				}
			},
			writeFile(path, outPutStr) {
				// 写入本地文件
				let fsm = wx.getFileSystemManager();
				fsm.writeFile({
					filePath: uni.env.USER_DATA_PATH + "/" + path,
					data: outPutStr,
					encoding: 'utf8',
					success: res => {
						uni.showModal({
							title: '提示',
							content: '文件已保存：' + path,
							cancelText: '我知道了',
							confirmText: '打开文件',
							success: function(res1) {
								if (res1.confirm) {
									uni.openDocument({
										filePath: `${uni.env.USER_DATA_PATH}/` + path,
										success: (sus) => {
											console.log("文件打开成功")
										}
									})
								}
							},
							fail: () => {
								uni.showToast({
									icon: 'error',
									title: '保存失败',
									duration: 1500
								})
							},
							complete: () => {
								uni.setClipboardData({
									data: path,
									success: function() {
										uni.showToast({
											icon: 'success',
											title: "已复制保存文件路径",
											duration: 1500
										})
									},
									fail: function(err) {}
								});
							}
						});
					},
					fail: res => {
						uni.showToast({
							icon: 'error',
							title: '文件下载失败',
							duration: 1500
						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	.progress-container {
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
		background: rgba(0, 0, 0, .2);
		width: 750rpx;
		height: 100vh;
		display: flex;
		align-items: center;
		justify-content: center;

		.progress-box {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 30rpx;

			.text {
				margin-bottom: 20rpx;
			}
		}
	}
</style>